<template>
    <div class="userHome-container">
        <!-- 面包屑 -->
        <Breadcrumb>
            <BreadcrumbItem to="/userHome">个人中心</BreadcrumbItem>
            <BreadcrumbItem>个人主页</BreadcrumbItem>
        </Breadcrumb>
        <!-- 个人头像区域 -->
        <div class="userInfo-header">
            <div class="userInfo-header-main">
                <div class="userInfo-avator">
                    <img :src="user.uAvatar" alt="">
                    <!-- 修改上传头像组件 -->
                    <div class="upload-file">
                      <form enctype="multipart/form-data">
                          <ImgCutter class="my-file"
                              :boxWidth="500"
                              :boxHeight="300"
                              :cutWidth="200"
                              :cutHeight="200"
                              :sizeChange="false"
                              v-on:cutDown="cutDown">
                              <button slot="open">
                                  修改头像
                              </button>
                          </ImgCutter>
                      </form>
                    </div>
                </div>
                <div class="userInfo-nickName">
                    <span><router-link :to="'/userInfo/' + user.uId">{{user.uName}}</router-link></span>
                </div>
                <div class="userInfo-statistic">
                    <div><router-link to="/">{{follow}} <br/> 关注</router-link></div>
                    <div><router-link to="/">{{fans}} <br/> 粉丝</router-link></div>
                </div>
            </div>
        </div>
        <Alert type="success">上次来过：{{user.uLastLogintime | dataFormat}}</Alert>
        <!-- 基本信息区域 -->
        <Divider orientation="left">基本信息</Divider>
        <div class="normal-info">
            <b-row>
                <b-col cols="12" sm="12" md="6" lg="6">
                    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                        <FormItem label="用户名" prop="username">
                            <Input v-model="formValidate.username" readonly />
                        </FormItem>
                        <FormItem label="昵称" prop="uName">
                            <Input v-model="formValidate.uName"/>
                        </FormItem>
                        <FormItem label="性别" prop="uGender">
                            <Input v-model="formValidate.uGender" placeholder="男/女"/>
                        </FormItem>
                        <FormItem label="标签" prop="uBio">
                            <Input v-model="formValidate.uBio"/>
                        </FormItem>
                        <FormItem label="生日" prop="uBirthday">
                            <DatePicker type="date" v-model="formValidate.uBirthday"></DatePicker>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" @click="saveUser('formValidate')">保存</Button>
                        </FormItem>
                    </Form>
                </b-col>
            </b-row>
        </div>
        <!-- 身份信息区域 -->
        <Divider orientation="left">身份信息</Divider>
        <div class="userAuth-info">
            <p class="red">tips：只有实名认证后才能在此平台购买和发布商品哦！</p>
            <!-- 当前用户未实名认证显示 -->
            <router-link to="/addUserAuth" v-show="userAuth==''">立即去实名认证</router-link>
            <!-- 当前用户已实名认证 -->
            <b-row v-show="userAuth">
                <b-col cols="12" sm="12" md="6" lg="6">
                    <div class="user-auth">
                        <p>姓名：{{userAuth.uaFullname}}</p>
                        <p>性别：{{userAuth.uaGender}}</p>
                        <p>地址：{{userAuth.uaAddr}}</p>
                        <p>生日：{{userAuth.uaBirthday}}</p>
                        <p>民族：{{userAuth.uaNation}}</p>
                    </div>
                    <Form :label-width="80">
                        <FormItem label="支付宝">
                            <Row>
                                <i-col span="11">
                                    <FormItem>
                                        <input readonly :value="userAuth.uaAlipay" />
                                    </FormItem>
                                </i-col>
                                <i-col span="5" style="margin-left:30px">
                                    <FormItem>
                                        <router-link to="/updateAlipay">去修改</router-link>
                                    </FormItem>
                                </i-col>
                            </Row>
                        </FormItem>
                    </Form>
                </b-col>
            </b-row>
        </div>
        <!-- 登录授权区域 -->
        <Divider orientation="left">登录授权</Divider>
        <div class="loginAuth-info">
            <p class="red">tips：授权后，您可以用手机号或邮箱号直接登录闲贰了</p>
            <p><Icon type="ios-call-outline" /> 手机号
                <span class="auth" v-if="hasPhone==false"><router-link to="/addLoginAuth">立即授权</router-link></span>
                <span class="auth" v-if="hasPhone">已授权</span>
            </p>
            <p><Icon type="ios-mail-outline" /> 邮箱号
                <span v-if="hasEmail==false"><router-link to="/addLoginAuth">立即授权</router-link></span>
                <span class="auth" v-if="hasEmail">已授权</span>
            </p>
        </div>
    </div>
</template>

<script>
// eslint-disable-next-line import/no-extraneous-dependencies
import ImgCutter from 'vue-img-cutter'
export default {
  name: 'userHome',
  data () {
    return {
      modal1: false,
      follow: 0, // 关注用户数
      fans: 0, // 粉丝数
      formValidate: {
        username: '',
        uName: '',
        uGender: '',
        uBio: '',
        uBirthday: ''
      },
      ruleValidate: {
        username: [
          { required: true, message: '用户名', trigger: 'blur' }
        ],
        uName: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        uGender: [
          { required: true, message: '性别不能为空', trigger: 'blur' }
        ],
        uBio: [
          { required: true, message: '签名不能为空', trigger: 'blur' }
        ],
        uBirthday: [
          { required: true, type: 'date', message: '生日不能为空', trigger: 'change' }
        ]
      },
      user: '', // 用户信息
      userAuth: '', // 用户实名认证信息
      identityType: [], // 身份认证信息
      hasPhone: false,
      hasEmail: false
    }
  },
  created () {
    this.findById()
    this.checkUserAuth()
    this.findIdentityType()
    this.findFollow()
    this.findFans()
  },
  methods: {
    // 上传头像
    cutDown (res) {
      const formData = new FormData()
      let file = res.file // 输出为file类型的文件对象
      formData.append('file', file)
      formData.append('uId', JSON.parse(localStorage.getItem('user')).uId)
      console.log(formData)
      this.$axios({
        url: 'users/updateAvatar',
        method: 'post',
        contentType: false,
        data: formData,
        processData: false,
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.findById()
        }
      })
        .catch(error => {
          console.log(error)
        })
    },
    // 根据用户Id查找个人信息
    findById () {
      this.$axios({
        url: 'users/findById/' + JSON.parse(localStorage.getItem('user')).uId,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.user = res.data.object
          this.formValidate.username = res.data.object.username
          this.formValidate.uName = res.data.object.uName
          this.formValidate.uGender = res.data.object.uGender
          this.formValidate.uBio = res.data.object.uBio
          this.formValidate.uBirthday = res.data.object.uBirthday
        }
      })
    },
    // 修改并保存用户个人信息
    saveUser (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$Message.success('Success!')
          this.$axios({
            url: 'users/update',
            method: 'get',
            params: {
              uId: JSON.parse(localStorage.getItem('user')).uId,
              uName: this.formValidate.uName,
              uGender: this.formValidate.uGender,
              uBio: this.formValidate.uBio,
              uBirthday: this.formValidate.uBirthday
            },
            headers: {
              Authorization: localStorage.getItem('token')
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.findById()
              this.$axios({
                url: 'users/findById/' + JSON.parse(localStorage.getItem('user')).uId,
                method: 'get',
                headers: {
                  Authorization: localStorage.getItem('token')
                }
              }).then(res => {
                if (res.data.code === 200) {
                  this.user = res.data.object
                  localStorage.setItem('user', JSON.stringify(this.user))
                  this.$router.go(0)
                }
              })
            }
          })
        } else {
          this.$Message.error('Fail!')
        }
      })
    },
    // 根据用户id检查该用户是否实名认证
    checkUserAuth () {
      this.$axios({
        url: 'userAuth/checkUserAuth',
        method: 'get',
        params: {
          uaUid: JSON.parse(localStorage.getItem('user')).uId
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.userAuth = res.data.object
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据用户id查询该用户登录授权信息
    findIdentityType () {
      this.$axios({
        url: 'userLoginAuths/findIdentityTypeByUid/' + JSON.parse(localStorage.getItem('user')).uId,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.identityType = res.data.list
          this.identityType.forEach(item => {
            if (item.ulaIdentityType === 'phone') {
              this.hasPhone = true
            } else if (item.ulaIdentityType === 'email') {
              this.hasEmail = true
            }
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据当前登录用户id查看关注的用户数
    findFollow () {
      this.$axios({
        url: 'follow/findFollowCount/' + JSON.parse(localStorage.getItem('user')).uId,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.follow = res.data.object
        }
      })
    },
    // 根据关注用户id查看粉丝的用户数
    findFans () {
      this.$axios({
        url: 'follow/findFansCount/' + JSON.parse(localStorage.getItem('user')).uId,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.fans = res.data.object
        }
      })
    }
  },
  components: {
    ImgCutter
  }
}
</script>

<style>

.my-file {
    width: 100%;
    height: 100px;
}
.my-file button {
    outline: 0;
    width: 100%;
    display: block;
    height: 100px;
    border-radius: 50%;
    background: rgba(0,0,0,0.3);
    cursor: pointer;
    border: none;
    font-size: 12px;
    line-height: 100px;
    text-align: center;
}

.userInfo-avator {
    width: 100px;
    height: 100px;
    margin:0 auto;
    position: relative;
    cursor: pointer;
}
.userInfo-avator img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border:5px solid #c9c9c9;
}
.upload-file {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    position: absolute;
    top:0;
    left:0;
    line-height: 100px;
    text-align: center;
    background: rgba(0,0,0,0.3);
    color: #fff;
    display: none;
    z-index: 10;
    cursor: pointer;
    transition: background .3s ease-in-out;
}
.userInfo-avator:hover .upload-file{
    display: block;
}
.user-auth {
    margin-left: 30px;
}
.user-auth p {
    margin-bottom: 5px;
}
.red {
    color: #ef4238;
}
.userInfo-header {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
}
.userInfo-header-main {
    min-width: 300px;
    height: 200px;
}
.userInfo-avator {
    width: 100px;
    height: 100px;
    margin:0 auto;
    position: relative;
    cursor: pointer;
}
.userInfo-avator img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border:5px solid #c9c9c9;
}
.userInfo-nickName {
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    text-align: center;
}
.userInfo-statistic {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.userInfo-statistic div {
    width: 70px;
    text-align: center;
}
.userInfo-statistic div:nth-child(1) {
    border-right: 1px solid #555;
}
.auth {
    color:chocolate;
}
</style>
